package com.easyOrder.core.push;

import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import org.apache.log4j.Logger;

public class IosDelivery implements PushDelivery {
	// true：表示的是产品发布推送服务
	// false：表示的是产品测试推送服务gateway.sandbox.push.apple.com/17.172.232.45,port=2195
	
	private Logger logger = Logger.getLogger(IosDelivery.class);
	
	private boolean production;

	private String key;

	private String password;

	public IosDelivery() {
	}

	public boolean getProduction() {
		return production;
	}

	public void setProduction(boolean value) {
		production = value;
	}

	public String getKey() {
		return key;
	}

	/**
	 * @param key the key to set
	 */
	public void setKey(String key) {
		this.key = key;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String value) {
		password = value;
	}

	public void send(Notification message) {
		PushNotificationManager pushManager = new PushNotificationManager();
		try {
			String filePath = IosDelivery.class.getClassLoader().getResource("/" + key).getFile();
			pushManager.initializeConnection(new AppleNotificationServerBasicImpl(filePath, password, production));
			int failed = 0;
			for (int i = 0; i < message.getRecipients().size(); i++) {
				Recipient recipient = message.getRecipients().get(i);
				Device device = new BasicDevice();
				device.setToken(recipient.getCode());

				PushNotificationPayload payLoad = PushNotificationPayload
						.complex();
				payLoad.addAlert(message.getContent());
				payLoad.addBadge(recipient.getMessageBadge());
				payLoad.addSound("default");
				PushedNotification notification = pushManager.sendNotification(
						device, payLoad, true);
				if (!notification.isSuccessful()) {
					failed++;
				}
			}
			pushManager.stopConnection();
			logger.info("推送 IOS 消息成功 "
					+ (message.getRecipients().size() - failed) + "，失败 "
					+ failed);
		} catch (Exception e) {
			logger.error(e, e);
		}
	}
}
